/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {
  let time = 0
  let ceng = 0
  const delEdgeZero = arr => {
    let left = 0
    let right = arr.length - 1
    while (arr[left] <= ceng || arr[right] <= ceng) {
      arr[left] <= ceng && arr.shift()
      arr[right] <= ceng && arr.pop()
      right = arr.length - 1
    }
    return arr
  }
  let canNext = !(height.filter(item => item > 0).length <= 1)
  while (canNext) {
    height = delEdgeZero(height)
    // height = height.map(item => {
    //   item--
    //   if (item < 0) {
    //     time++
    //   }
    //   return item
    // })
    ceng++
    canNext = !(
      height.filter(item => {
        item < ceng && time++
        return item > ceng
      }).length <= 1
    )
  }
  return time
}

console.log(trap([5, 4, 1, 2]))
